<!--  -->
<template>
  <div id="main">
    <h2>宣传图片管理</h2>
    <el-button type="primary" style="margin:20px" @click="handleOpen('添加宣传图片',1)">添加宣传图片</el-button>
    <!-- <div id="search-card">
      <div id="search-content">
        <el-form v-model="search" :inline="true">

          <el-form-item label="昵称">
            <el-input v-model="search.username" />
          </el-form-item>

          <el-form-item label="所属机构">
            <el-select v-model="search.orgId" placeholder="请选择">
              <el-option
                v-for="o in org"
                :key="o.orgId"
                :value="o.orgId"
                :label="o.orgName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="用户角色">
            <el-select v-model="search.userGroup" placeholder="请选择">
              <el-option key="1" label="系统管理员" value="1" />
              <el-option key="2" label="代理人" value="2" />
              <el-option key="3" label="机构管理员" value="3" />
              <el-option key="4" label="分支机构管理员" value="4" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="margin-left:10px" @click="conditionQuery">查找</el-button>
            <el-button icon="el-icon-refresh" circle @click="fetchData()" />
          </el-form-item>

        </el-form>
      </div>

    </div> -->

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >

        <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="publicityPicturesPic"
          label="宣传图片"
        >
          <template slot-scope="Scope">
            <img :src="Scope.row.publicityPicturesPic" width="320px" height="180px">
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="publicityPicturesGroup"
          label="图片所属组"
        />

        <el-table-column
          align="center"
          prop="publicityPicturesOrder"
          label="图片顺序"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改管理员用户',2,Scope.row.publicityPicturesId)">详情</el-button>
            <!-- <el-button type="primary" icon="el-icon-edit" @click="handlePass(Scope.row.publicityPicturesId)">通过</el-button> -->
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.publicityPicturesId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog title="宣传图片详情" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="publicityPictures" :model="publicityPictures" label-position="top">

        <el-form-item prop="publicityPicturesGroup" label="图片所属组" :label-width="formLabelWidth">
          <el-input v-model="publicityPictures.publicityPicturesGroup" maxlength="5" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
        <el-form-item prop="publicityPicturesOrder" label="图片顺序" :label-width="formLabelWidth">
          <el-input v-model="publicityPictures.publicityPicturesOrder" maxlength="5" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
        <!-- <el-form-item prop="agentApplicationReason" label="申请理由" :label-width="formLabelWidth">
          <el-input v-model="agentApplication.agentApplicationReason" autocomplete="off" readonly />
        </el-form-item> -->
        <el-form-item label="宣传图片">
          <el-upload
            class="avatar-uploader"
            name="files"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType==2" type="primary" @click="handleUpdate()">修 改</el-button>
        <el-button v-if="editType==1" type="primary" @click="handleAdd()">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getAllPublicityPictures, addPublicityPictures, getPublicityPicturesById, deletePublicityPicturesById, updatePublicityPictures } from '@/api/publicityPictures'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      url: process.env.VUE_APP_BASE_API + 'file/',
      list: [],
      listLoading: false,
      dialogFormVisible: false,
      editType: 1, // 1 添加 2 修改
      search: {},
      mohu: '',
      publicityPictures: {},
      formLabelWidth: '200px',
      fileList: [],
      imageUrl: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchData()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.publicityPictures.publicityPicturesPic = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {
      this.listLoading = true
      getAllPublicityPictures().then((resp) => {
        this.list = resp.obj
        this.listLoading = false
      })
    },
    handleDelete(id) {
      this.$confirm('确认删除该图片？').then(() => deletePublicityPicturesById(id).then((data) => {
        this.$notify({
          title: '操作成功',
          type: 'success'
        })
        const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
        const page = this.currentPage > totalPage ? totalPage : this.currentPage
        this.currentPage = this.currentPage < 1 ? 1 : page
        this.fetchData()
      }))
    },
    handleOpen(title, type, id) {
      this.imageUrl = ''
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getPublicityPicturesById(id).then((resp) => {
          this.publicityPictures = resp.obj
          this.imageUrl = resp.obj.publicityPicturesPic
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.publicityPictures = {}
    },
    handleAdd() {
      addPublicityPictures(this.publicityPictures).then((resp) => {
        this.$notify({
          title: '操作成功',
          type: 'success'
        })
        this.fetchData()
        this.publicityPictures = {}
        this.dialogFormVisible = false
      })
    },
    handleUpdate() {
      updatePublicityPictures(this.publicityPictures).then((resp) => {
        this.$notify({
          title: '更新成功',
          type: 'success'
        })
        this.fetchData()
        this.publicityPictures = {}
        this.dialogFormVisible = false
      })
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
#main{
  margin-left: 5px;
  margin-right: 5px;
}
#table-area{
  margin-left: 10px;
  margin-right: 10px;
}
#search-card {
  line-height: 0px;
  text-align: right;
  width: 100%;
  height: 70px;
  overflow-x: hidden;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 480px;
  height: 270px;
  line-height: 270px;
  text-align: center;
}
.avatar {
  width: 480px;
  height: 270px;
  display: block;
}
</style>
